#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
采购管理模块
负责食材采购订单的管理
"""

import tkinter as tk
from tkinter import ttk, messagebox
from datetime import datetime, timedelta
import random

class ProcurementManager:
    def __init__(self, data_manager):
        self.data_manager = data_manager
        
    def create_ui(self, parent):
        """创建采购管理界面"""
        # 主框架
        main_frame = tk.Frame(parent, bg='white')
        main_frame.pack(fill='both', expand=True, padx=20, pady=20)
        
        # 标题
        title_label = tk.Label(main_frame, text="采购管理", 
                              font=('微软雅黑', 16, 'bold'),
                              bg='white', fg='#2c3e50')
        title_label.pack(pady=10)
        
        # 操作按钮框架
        button_frame = tk.Frame(main_frame, bg='white')
        button_frame.pack(fill='x', pady=10)
        
        tk.Button(button_frame, text="新增采购订单", 
                 command=self.add_order_dialog,
                 font=('微软雅黑', 10),
                 bg='#27ae60', fg='white',
                 width=15).pack(side='left', padx=5)
        
        tk.Button(button_frame, text="修改订单", 
                 command=self.edit_order_dialog,
                 font=('微软雅黑', 10),
                 bg='#3498db', fg='white',
                 width=15).pack(side='left', padx=5)
        
        tk.Button(button_frame, text="删除订单", 
                 command=self.delete_order,
                 font=('微软雅黑', 10),
                 bg='#e74c3c', fg='white',
                 width=15).pack(side='left', padx=5)
        
        tk.Button(button_frame, text="刷新列表", 
                 command=self.refresh_list,
                 font=('微软雅黑', 10),
                 bg='#95a5a6', fg='white',
                 width=15).pack(side='left', padx=5)
        
        # 搜索框架
        search_frame = tk.Frame(main_frame, bg='white')
        search_frame.pack(fill='x', pady=10)
        
        tk.Label(search_frame, text="搜索:", font=('微软雅黑', 10),
                bg='white').pack(side='left', padx=5)
        
        self.search_var = tk.StringVar()
        search_entry = tk.Entry(search_frame, textvariable=self.search_var,
                               font=('微软雅黑', 10), width=20)
        search_entry.pack(side='left', padx=5)
        search_entry.bind('<KeyRelease>', self.on_search)
        
        # 状态筛选
        tk.Label(search_frame, text="状态:", font=('微软雅黑', 10),
                bg='white').pack(side='left', padx=(20, 5))
        
        self.status_var = tk.StringVar(value="全部")
        status_combo = ttk.Combobox(search_frame, textvariable=self.status_var,
                                   values=["全部", "待确认", "已确认", "配送中", "已完成"],
                                   width=10, state="readonly")
        status_combo.pack(side='left', padx=5)
        status_combo.bind('<<ComboboxSelected>>', self.on_search)
        
        # 订单列表框架
        list_frame = tk.Frame(main_frame, bg='white')
        list_frame.pack(fill='both', expand=True, pady=10)
        
        # 创建Treeview
        columns = ("订单号", "商品名称", "供应商", "数量", "单价", "总金额", "订单日期", "预计送达", "状态")
        self.tree = ttk.Treeview(list_frame, columns=columns, show='headings', height=15)
        
        # 设置列标题和宽度
        column_widths = [100, 120, 120, 80, 80, 100, 100, 100, 80]
        for i, (col, width) in enumerate(zip(columns, column_widths)):
            self.tree.heading(col, text=col)
            self.tree.column(col, width=width, anchor='center')
        
        # 滚动条
        scrollbar_y = ttk.Scrollbar(list_frame, orient='vertical', command=self.tree.yview)
        scrollbar_x = ttk.Scrollbar(list_frame, orient='horizontal', command=self.tree.xview)
        self.tree.configure(yscrollcommand=scrollbar_y.set, xscrollcommand=scrollbar_x.set)
        
        # 布局
        self.tree.pack(side='left', fill='both', expand=True)
        scrollbar_y.pack(side='right', fill='y')
        scrollbar_x.pack(side='bottom', fill='x')
        
        # 加载数据
        self.refresh_list()
        
    def refresh_list(self):
        """刷新订单列表"""
        # 清空现有数据
        for item in self.tree.get_children():
            self.tree.delete(item)
            
        # 获取订单数据
        orders = self.data_manager.get_procurement_orders()
        suppliers = {s["id"]: s["name"] for s in self.data_manager.get_suppliers()}
        
        # 应用搜索和筛选
        search_text = self.search_var.get().lower()
        status_filter = self.status_var.get()
        
        for order in orders:
            # 搜索筛选
            if search_text and search_text not in order["item_name"].lower():
                continue
                
            # 状态筛选
            if status_filter != "全部" and order["status"] != status_filter:
                continue
                
            supplier_name = suppliers.get(order["supplier_id"], "未知供应商")
            
            self.tree.insert('', 'end', values=(
                order["id"],
                order["item_name"],
                supplier_name,
                order["quantity"],
                f"¥{order['unit_price']:.2f}",
                f"¥{order['total_amount']:.2f}",
                order["order_date"],
                order["expected_delivery"],
                order["status"]
            ))
            
    def on_search(self, event=None):
        """搜索事件处理"""
        self.refresh_list()
        
    def add_order_dialog(self):
        """新增采购订单对话框"""
        dialog = tk.Toplevel()
        dialog.title("新增采购订单")
        dialog.geometry("500x600")
        dialog.configure(bg='white')
        dialog.transient()
        dialog.grab_set()
        
        # 居中显示
        dialog.update_idletasks()
        x = (dialog.winfo_screenwidth() // 2) - (dialog.winfo_width() // 2)
        y = (dialog.winfo_screenheight() // 2) - (dialog.winfo_height() // 2)
        dialog.geometry(f"+{x}+{y}")
        
        # 表单框架
        form_frame = tk.Frame(dialog, bg='white')
        form_frame.pack(fill='both', expand=True, padx=20, pady=20)
        
        # 订单号（自动生成）
        row = 0
        tk.Label(form_frame, text="订单号:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        order_id = f"PO{str(len(self.data_manager.get_procurement_orders()) + 1).zfill(4)}"
        tk.Label(form_frame, text=order_id, font=('微软雅黑', 10),
                bg='white', fg='#3498db').grid(row=row, column=1, sticky='w', pady=5)
        
        # 商品选择
        row += 1
        tk.Label(form_frame, text="商品:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        item_var = tk.StringVar()
        items = self.data_manager.get_inventory_items()
        item_names = [f"{item['name']} ({item['id']})" for item in items]
        item_combo = ttk.Combobox(form_frame, textvariable=item_var,
                                 values=item_names, width=30, state="readonly")
        item_combo.grid(row=row, column=1, sticky='w', pady=5)
        
        # 数量
        row += 1
        tk.Label(form_frame, text="采购数量:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        quantity_var = tk.StringVar()
        quantity_entry = tk.Entry(form_frame, textvariable=quantity_var,
                                 font=('微软雅黑', 10), width=20)
        quantity_entry.grid(row=row, column=1, sticky='w', pady=5)
        
        # 单价
        row += 1
        tk.Label(form_frame, text="单价:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        price_var = tk.StringVar()
        price_entry = tk.Entry(form_frame, textvariable=price_var,
                              font=('微软雅黑', 10), width=20)
        price_entry.grid(row=row, column=1, sticky='w', pady=5)
        
        # 预计送达日期
        row += 1
        tk.Label(form_frame, text="预计送达日期:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        delivery_var = tk.StringVar(value=(datetime.now() + timedelta(days=3)).strftime("%Y-%m-%d"))
        delivery_entry = tk.Entry(form_frame, textvariable=delivery_var,
                                 font=('微软雅黑', 10), width=20)
        delivery_entry.grid(row=row, column=1, sticky='w', pady=5)
        
        # 状态
        row += 1
        tk.Label(form_frame, text="状态:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        status_var = tk.StringVar(value="待确认")
        status_combo = ttk.Combobox(form_frame, textvariable=status_var,
                                   values=["待确认", "已确认", "配送中", "已完成"],
                                   width=18, state="readonly")
        status_combo.grid(row=row, column=1, sticky='w', pady=5)
        
        # 自动填充单价
        def on_item_select(event):
            selected = item_var.get()
            if selected:
                item_id = selected.split('(')[1].split(')')[0]
                for item in items:
                    if item['id'] == item_id:
                        price_var.set(str(item['unit_price']))
                        break
        
        item_combo.bind('<<ComboboxSelected>>', on_item_select)
        
        # 按钮框架
        button_frame = tk.Frame(form_frame, bg='white')
        button_frame.grid(row=row+1, column=0, columnspan=2, pady=20)
        
        def save_order():
            try:
                # 验证输入
                if not item_var.get():
                    messagebox.showerror("错误", "请选择商品")
                    return
                    
                if not quantity_var.get() or not quantity_var.get().isdigit():
                    messagebox.showerror("错误", "请输入有效的数量")
                    return
                    
                if not price_var.get():
                    messagebox.showerror("错误", "请输入单价")
                    return
                
                # 获取选中的商品信息
                selected_item = item_var.get()
                item_id = selected_item.split('(')[1].split(')')[0]
                item_name = selected_item.split(' (')[0]
                
                # 找到对应的供应商
                supplier_id = None
                for item in items:
                    if item['id'] == item_id:
                        supplier_id = item['supplier_id']
                        break
                
                quantity = int(quantity_var.get())
                unit_price = float(price_var.get())
                total_amount = quantity * unit_price
                
                # 创建订单
                order = {
                    "id": order_id,
                    "item_id": item_id,
                    "item_name": item_name,
                    "supplier_id": supplier_id,
                    "quantity": quantity,
                    "unit_price": unit_price,
                    "total_amount": total_amount,
                    "order_date": datetime.now().strftime("%Y-%m-%d"),
                    "expected_delivery": delivery_var.get(),
                    "status": status_var.get()
                }
                
                # 保存订单
                self.data_manager.add_procurement_order(order)
                messagebox.showinfo("成功", "采购订单已添加")
                dialog.destroy()
                self.refresh_list()
                
            except ValueError:
                messagebox.showerror("错误", "请输入有效的数字")
            except Exception as e:
                messagebox.showerror("错误", f"保存失败: {str(e)}")
        
        tk.Button(button_frame, text="保存", command=save_order,
                 font=('微软雅黑', 10), bg='#27ae60', fg='white',
                 width=10).pack(side='left', padx=10)
        
        tk.Button(button_frame, text="取消", command=dialog.destroy,
                 font=('微软雅黑', 10), bg='#95a5a6', fg='white',
                 width=10).pack(side='left', padx=10)
        
    def edit_order_dialog(self):
        """修改采购订单对话框"""
        selected = self.tree.selection()
        if not selected:
            messagebox.showwarning("警告", "请先选择要修改的订单")
            return
            
        # 获取选中的订单
        item = self.tree.item(selected[0])
        order_id = item['values'][0]
        
        # 找到对应的订单数据
        orders = self.data_manager.get_procurement_orders()
        current_order = None
        for order in orders:
            if order['id'] == order_id:
                current_order = order
                break
                
        if not current_order:
            messagebox.showerror("错误", "未找到订单数据")
            return
        
        # 创建修改对话框（类似新增对话框，但预填充数据）
        dialog = tk.Toplevel()
        dialog.title("修改采购订单")
        dialog.geometry("500x600")
        dialog.configure(bg='white')
        dialog.transient()
        dialog.grab_set()
        
        # 居中显示
        dialog.update_idletasks()
        x = (dialog.winfo_screenwidth() // 2) - (dialog.winfo_width() // 2)
        y = (dialog.winfo_screenheight() // 2) - (dialog.winfo_height() // 2)
        dialog.geometry(f"+{x}+{y}")
        
        # 表单框架
        form_frame = tk.Frame(dialog, bg='white')
        form_frame.pack(fill='both', expand=True, padx=20, pady=20)
        
        # 订单号（只读）
        row = 0
        tk.Label(form_frame, text="订单号:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        tk.Label(form_frame, text=order_id, font=('微软雅黑', 10),
                bg='white', fg='#3498db').grid(row=row, column=1, sticky='w', pady=5)
        
        # 商品（只读）
        row += 1
        tk.Label(form_frame, text="商品:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        tk.Label(form_frame, text=current_order['item_name'], font=('微软雅黑', 10),
                bg='white', fg='#3498db').grid(row=row, column=1, sticky='w', pady=5)
        
        # 数量
        row += 1
        tk.Label(form_frame, text="采购数量:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        quantity_var = tk.StringVar(value=str(current_order['quantity']))
        quantity_entry = tk.Entry(form_frame, textvariable=quantity_var,
                                 font=('微软雅黑', 10), width=20)
        quantity_entry.grid(row=row, column=1, sticky='w', pady=5)
        
        # 单价
        row += 1
        tk.Label(form_frame, text="单价:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        price_var = tk.StringVar(value=str(current_order['unit_price']))
        price_entry = tk.Entry(form_frame, textvariable=price_var,
                              font=('微软雅黑', 10), width=20)
        price_entry.grid(row=row, column=1, sticky='w', pady=5)
        
        # 预计送达日期
        row += 1
        tk.Label(form_frame, text="预计送达日期:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        delivery_var = tk.StringVar(value=current_order['expected_delivery'])
        delivery_entry = tk.Entry(form_frame, textvariable=delivery_var,
                                 font=('微软雅黑', 10), width=20)
        delivery_entry.grid(row=row, column=1, sticky='w', pady=5)
        
        # 状态
        row += 1
        tk.Label(form_frame, text="状态:", font=('微软雅黑', 10),
                bg='white').grid(row=row, column=0, sticky='w', pady=5)
        
        status_var = tk.StringVar(value=current_order['status'])
        status_combo = ttk.Combobox(form_frame, textvariable=status_var,
                                   values=["待确认", "已确认", "配送中", "已完成"],
                                   width=18, state="readonly")
        status_combo.grid(row=row, column=1, sticky='w', pady=5)
        
        # 按钮框架
        button_frame = tk.Frame(form_frame, bg='white')
        button_frame.grid(row=row+1, column=0, columnspan=2, pady=20)
        
        def update_order():
            try:
                # 验证输入
                if not quantity_var.get() or not quantity_var.get().isdigit():
                    messagebox.showerror("错误", "请输入有效的数量")
                    return
                    
                if not price_var.get():
                    messagebox.showerror("错误", "请输入单价")
                    return
                
                quantity = int(quantity_var.get())
                unit_price = float(price_var.get())
                total_amount = quantity * unit_price
                
                # 更新订单
                updated_order = current_order.copy()
                updated_order.update({
                    "quantity": quantity,
                    "unit_price": unit_price,
                    "total_amount": total_amount,
                    "expected_delivery": delivery_var.get(),
                    "status": status_var.get()
                })
                
                # 保存更新
                self.data_manager.update_procurement_order(order_id, updated_order)
                messagebox.showinfo("成功", "采购订单已更新")
                dialog.destroy()
                self.refresh_list()
                
            except ValueError:
                messagebox.showerror("错误", "请输入有效的数字")
            except Exception as e:
                messagebox.showerror("错误", f"更新失败: {str(e)}")
        
        tk.Button(button_frame, text="保存", command=update_order,
                 font=('微软雅黑', 10), bg='#27ae60', fg='white',
                 width=10).pack(side='left', padx=10)
        
        tk.Button(button_frame, text="取消", command=dialog.destroy,
                 font=('微软雅黑', 10), bg='#95a5a6', fg='white',
                 width=10).pack(side='left', padx=10)
        
    def delete_order(self):
        """删除采购订单"""
        selected = self.tree.selection()
        if not selected:
            messagebox.showwarning("警告", "请先选择要删除的订单")
            return
            
        # 获取选中的订单
        item = self.tree.item(selected[0])
        order_id = item['values'][0]
        
        if messagebox.askyesno("确认", f"确定要删除订单 {order_id} 吗？"):
            self.data_manager.delete_procurement_order(order_id)
            messagebox.showinfo("成功", "订单已删除")
            self.refresh_list() 